import { createRouter,createWebHistory } from 'vue-router'
import Home from './views/Home.vue'
import Login from './views/Login.vue'
import Signup from './views/Signup.vue'
import axios from 'axios'
import ColumnDetail from './views/ColumnDetail.vue'
import createPost from './views/CreatePost.vue'
import PostDetail from './views/PostDetail.vue'
import EditProfile from './views/EditProfile.vue'
import store from './store'
const routerHistory = createWebHistory()
const router = createRouter({
    history:routerHistory,
    routes:[
        {
            path:'/',
            name:'home',
            component:Home
        },
        {
            path:'/login',
            name:'login',
            component:Login,
            meta:{redirectAlreadyLogin:true}    //已经登陆了,再访问登录页面的时候需要重定向到首页
        },
        {
            path:'/column/:id',
            name:'column',
            component:ColumnDetail
        },
        {
            path:'/create',
            name:'create',
            component:createPost,
            meta:{requireLogin:true}    //访问此路由必须要登陆
        },
        {
            path:'/signup',
            name:'signup',
            component:Signup,
            meta:{redirectAlreadyLogin:true}
        },
        {
            path:'/PostDetail/:id',
            name:'PostDetail',
            component:PostDetail
        },
        {
            path:'/editProfile',
            name:'editProfile',
            component:EditProfile,
            meta:{requireLogin:true}
        }
    ]
})

router.beforeEach((to,from,next)=>{ //路由守卫
    const {user,token} = store.state
    const {requireLogin,redirectAlreadyLogin} =to.meta
    if(!user.isLogin){  //目前没登录
        if(token){  //token有值
            axios.defaults.headers.common.Authorization=`Bearer ${token}`   //设置头信息
            store.dispatch('fetchCurrentUser').then(()=>{   //获取用户信息
                if(redirectAlreadyLogin){   //已经登陆需要重定向
                    next('/')
                }else{  //已经登陆，不需要重定向，继续下面的操作即可
                    next()
                }
            }).catch(e=>{   //token失效
                console.log(e)
                store.commit('logout')
                next('login')   //跳转到登陆页面
            })
        }else{  //token没值
            if(requireLogin){   //需要登陆
                next('login')   //跳转到登陆页面
            }else{          //不需要登录也可以访问
                next()      //继续
            }
        }
    }else{ //目前登陆了
        if(redirectAlreadyLogin){   //已经登陆需要重定向
            next('/')
        }else{
            next()  //已经登陆，不需要重定向，继续下面的操作即可
        }
    }
})

export default router